package com.study.hot

import android.app.Application
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import com.study.base.BaseApp
import com.study.base.ServiceFactory

/**
 * <pre>
 *     author : fauks
 *     time   : 2020/03/21
 *     desc   :
 * </pre>
 */
class HotApp : BaseApp() {

    override fun onCreate() {
        super.onCreate()
        initModuleData(this)

        // 需要通过ProcessLifecycleOwner获取LifecycleOwner
        ProcessLifecycleOwner.get().lifecycle.addObserver(ApplicationLifecycleObserver())
    }

    override fun initModuleApp(application: Application) {
        ServiceFactory.INSTANCE.hotService = HotServiceImpl()
    }

    override fun initModuleData(application: Application) {

    }

    /**
     * Application生命周期观察，提供整个应用进程的生命周期
     *
     * Lifecycle.Event.ON_CREATE只会分发一次，Lifecycle.Event.ON_DESTROY不会被分发
     *
     * 第一个Activity进入时，ProcessLifecycleOwner将分派Lifecycle.Event.ON_START, Lifecycle.Event.ON_RESUME。
     * 而Lifecycle.Event.ON_PAUSE, Lifecycle.Event.ON_STOP，将在最后一个Activity退出后后延迟分发。如果由于配置更改而销毁并重新创建活动，则此延迟足以保证ProcessLifecycleOwner不会发送任何事件。
     *
     * 作用：监听应用程序进入前台或后台
     */
    class ApplicationLifecycleObserver : LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onAppForeground() {
            Log.i("fauks", "Hot 进入前台")
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onAppBackground() {
            Log.i("fauks", "Hot 进入后台")
        }
    }
}